#include "Transmiter.h"


// 初始化Winsock (仅Windows需要)
#ifdef _WIN32
void TcpSocket::init_winsock() 
{
    WSADATA wsaData;
    int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (result != 0) {
        std::cerr << "WSAStartup failed: " << result << std::endl;
        exit(EXIT_FAILURE);
    }
}
#endif

// 创建并连接socket的辅助函数
TcpSocket::SocketType TcpSocket::create_and_listen_socket(int port) 
{
    #ifdef _WIN32
        init_winsock();
    #endif

    sockfd_server = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd_server == INVALID_SOCKET) {
        std::cerr << "Socket creation failed: " << WSAGetLastError() << "\n";
        WSACleanup();
        return false;
    }

    sockaddr_in serverAddr{};
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(port);

    if (bind(sockfd_server, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) 
    {
        std::cerr << "Bind failed: " << WSAGetLastError() << "\n";
        closesocket(sockfd_server);
        WSACleanup();
        return false;
    }

    if (listen(sockfd_server, 1) == SOCKET_ERROR) 
    // if (listen(sockfd_, SOMAXCONN) == SOCKET_ERROR) 
    {
        std::cerr << "Listen failed: " << WSAGetLastError() << "\n";
        closesocket(sockfd_server);
        WSACleanup();
        return false;
    }

    running_ = true;

    std::packaged_task<void()> task_listener(std::bind(&TcpSocket::Listener_Loop, this));
    listener_thread_ = std::thread(std::move(task_listener));

    return sockfd_server;
}

void TcpSocket::Listener_Loop() 
{
    while(true)
    {
        sockaddr_in clientAddr{};
        int addrLen = sizeof(clientAddr);
        
        clientSocket = accept(sockfd_server, (sockaddr*)&clientAddr, &addrLen);
        if (clientSocket == INVALID_SOCKET) {
            if (running_) {
                std::cerr << "Accept failed: " << WSAGetLastError() << "\n";
            }
            continue;
        }

        char clientIP[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, &clientAddr.sin_addr, clientIP, INET_ADDRSTRLEN);
        std::cout << "Client connected: " << clientIP << ":" << ntohs(clientAddr.sin_port) << "\n";
        logger_->info("Client connected: {0} : {1}",clientIP,ntohs(clientAddr.sin_port));
        // {
        //     std::lock_guard<std::mutex> lock(clientsMutex_);
        //     clients_.insert(clientSocket);
        // }

        //创建发送线程和接收线程
        Start_Transmit();

        while(running_)
        {
            std::this_thread::sleep_for(std::chrono::seconds(5));
        }

        break;
    }
}




// 创建并连接socket的辅助函数
bool TcpSocket::create_connect_to_server(int port) 
{
    #ifdef _WIN32
        init_winsock();
    #endif

    // 创建套接字
    clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (clientSocket == INVALID_SOCKET) {
        std::cerr << "Socket creation failed. Error: " << WSAGetLastError() << std::endl;
        WSACleanup();
        return false;
    }

    // 设置服务器地址信息
    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(8080);  // 服务器端口
    
    // 将IP地址从字符串转换为二进制格式
    if (inet_pton(AF_INET, "192.168.1.30", &serverAddr.sin_addr) <= 0) {
        std::cerr << "Invalid address/Address not supported. Error: " << WSAGetLastError() << std::endl;
        closesocket(clientSocket);
        WSACleanup();
        return false;
    }

    // 连接到服务器
    if (connect(clientSocket, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
        std::cerr << "Connection failed. Error: " << WSAGetLastError() << std::endl;
        closesocket(clientSocket);
        WSACleanup();
        return false;
    }

    std::cout << "Connected to server!" << std::endl;

    //创建发送线程和接收线程
    Start_Transmit();

    return true;
}





